//
//  NetworkHandlerV2.m
//  UI20_NSURLSession
//
//  Created by 李劲成 on 16/4/6.
//  Copyright © 2016年 ljc. All rights reserved.
//

#import "NetworkHandlerV2.h"

@interface NetworkHandlerV2 ()

@property (nonatomic, assign) id <NetworkHandlerV2Delegate> delegate;

@end

@implementation NetworkHandlerV2
/** 通过NSURLSession实现网络请求. */
+(void)networkHandlerV2WithURL:(NSString *)urlString delegate:(id<NetworkHandlerV2Delegate>)delegate {
    
    // core API:
    // 将字符串进行转码(URL中不能含有中文等字符)
    NSString *temp = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSURLSession *sesstion = [NSURLSession sharedSession];
    
    NSURL *url = [NSURL URLWithString:temp];
    // session 中添加 data 任务
    NSURLSessionDataTask *task = [sesstion dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        
        // 进行数据解析.
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        // 通过 delegate 回调
        
            // 回到主线程 GCD
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if ([delegate respondsToSelector:@selector(didFinishV2Completion:)]) {
                    
                [delegate didFinishV2Completion:result];
                    
                }
                
            });
            
        
    }];
    // 任务开始执行.
    [task resume];
}




@end
